import { Button, Form, Input, message, Select, Upload } from "antd"
import Layout from "../core/Layout"
import axios from 'axios'
import { API } from "../../config"
import { isAuth } from "../../helpers/auth"
import { useHistory } from "react-router-dom"
import { UploadOutlined } from "@ant-design/icons"
import { useState } from "react"
import useGetCategories from "../../helpers/getCategories"

export default function AddProduct() {
    const [form] = Form.useForm()
    const categories = useGetCategories()
    const [photoFile, setPhotoFile] = useState([])
    const history = useHistory()
    const props = {
        beforeUpload (value) {
            setPhotoFile(value)
            return false
        }
    }
    const handleOnFinish = async value => {
        const fordata = new FormData()
        for (let key in value) {
            fordata.append(key, value[key])
        }
        fordata.append('photo', photoFile)

            await axios.post(`${API}/product/create/${isAuth().user._id}`, fordata, {
                headers: {
                    Authorization: `Bearer ${isAuth().token}`
                }
            }).then(() => {
                message.success(`添加成功`)
                form.resetFields()
                history.push('/admin/dashboard')
            })
    }
    return <Layout title='添加商品'>
        <Form form={form} onFinish={handleOnFinish}  initialValues={{category: '-1'}}>
            <Form.Item>
                <Upload {...props}>
                    <Button icon={<UploadOutlined />}>上传商品封面</Button>
                </Upload>
            </Form.Item>
            <Form.Item label='商品名称' name='name' >
                <Input />
            </Form.Item>
            <Form.Item label='商品描述' name='description'>
                <Input />
            </Form.Item>
            <Form.Item label='商品价格' name='price'>
                <Input />
            </Form.Item>
            <Form.Item label='商品分类' name='category'>
                <Select>
                    <Select.Option value='-1'>请选择类型</Select.Option>
                    {
                        categories.map(({name, _id}) => (
                            <Select.Option key={name} value={_id}>{name}</Select.Option>
                        ))
                    }
                </Select>
            </Form.Item>
            <Form.Item label='商品数量' name='quantity'>
                <Input />
            </Form.Item>
            <Form.Item label='是否需要运输' name='shipping'>
                <Select>
                    <Select.Option value='true'>是</Select.Option>
                    <Select.Option value='false'>否</Select.Option>
                </Select>
            </Form.Item>
            <Form.Item>
                <Button type="primary" htmlType='submit'>添加商品</Button>
            </Form.Item>
        </Form>
    </Layout>
}